<?php

namespace app\controllers;

use app\librarys\BaseController;
use app\librarys\Tools;
use app\models\Manager;
use app\models\Open;
use app\models\Permission;
use yii\data\Pagination;

class OpenController extends BaseController
{
    public function actionIndex()
    {
        $institutionCode = \Yii::$app->request->get('institution_code', null);
        if (!isset($institutionCode)) {
            $institutionCode = Manager::getCurrentManager()['institution_code'];
        }
        if (!Permission::hasInstitutionPermission($institutionCode)) {
            throw new \Exception('无法查看此机构数据!');
        }

        $item = Open::getConfig($institutionCode);

        return $this->render('index', ['item' => $item, 'current_institution_code' => $institutionCode]);
    }

    public function actionCreateAccountTokenHandler()
    {
        $account = Open::createAccount();
        $token = Tools::getRandomString(32);

        $data = [
            'account' => $account,
            'token' => $token
        ];

        return $this->renderJson($data, 0, '');
    }

    public function actionSetOpenConfigHandler()
    {
        $data = \Yii::$app->request->post();
        $result = Open::setConfig($data);
        return $this->renderJson();
    }
}